package com.itheima.controller.servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.itheima.domain.User;
import com.itheima.service.UserService;
import com.itheima.service.impl.UserServiceImpl;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.Converter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/userServlet")
public class UserServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        ConvertUtils.register(new Converter() {
            @Override
            public Object convert(Class aClass, Object o) {
                if (o == null) {
                    return null;
                }
                Date date = null;
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                String str = (String) o;
                try {
                    date = sdf.parse(str);
                } catch (ParseException e) {
                    e.printStackTrace();
                }

                return date;
            }
        }, Date.class);
        String method = request.getParameter("method");
        Map resultMap = null;
        if ("findByPage".equals(method)) {
            resultMap = this.findByPage(request, response);
        } else if ("add".equals(method)) {
            resultMap = this.add(request, response);
        } else if ("update".equals(method)) {
            resultMap = this.update(request, response);
        } else if ("delete".equals(method)) {
            resultMap = this.delete(request, response);
        } else if ("findByUsernameAndPassword".equals(method)){
            resultMap = this.findByUsernameAndPassword(request,response);
        }else if ("logout".equals(method)){
            resultMap = this.logout(request,response);
        }else if ("findUsername".equals(method)){
            resultMap = this.findUsername(request,response);
        }else if ("logoutTwo".equals(method)){
            resultMap = this.logoutTwo(request,response);
        }

        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(resultMap);
        response.getWriter().write(json);
    }

    private Map logoutTwo(HttpServletRequest request, HttpServletResponse response) {
        Map resultMap = new HashMap();
        try {
            request.getSession().removeAttribute("user");
            resultMap.put("flag",true);
            resultMap.put("resultData","/login.html");
        } catch (Exception e) {
            resultMap.put("flag",false);
            resultMap.put("resultData","/login.html");
            e.printStackTrace();
        }
        return resultMap;
    }

    private Map findUsername(HttpServletRequest request, HttpServletResponse response) {
        Map resultMap = new HashMap();
        try {
            User user = (User) request.getSession().getAttribute("user");
            String userName = user.getUserName();
            resultMap.put("flag",true);
            resultMap.put("resultData",userName);
        } catch (Exception e) {
            resultMap.put("flag",false);
            resultMap.put("message","内部错误!");
            e.printStackTrace();
        }
        return resultMap;
    }

    private Map logout(HttpServletRequest request, HttpServletResponse response) {
        Map resultMap = new HashMap();
        try {
            request.getSession().removeAttribute("user");
            response.sendRedirect("login.html");
        } catch (IOException e) {
            resultMap.put("flag",false);
            resultMap.put("message","退出失败!");
            e.printStackTrace();
        }
        return resultMap;
    }

    private Map findByUsernameAndPassword(HttpServletRequest request, HttpServletResponse response) {
        Map resultMap = new HashMap();
        try {
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            User user = userService.findByUsernameAndPassword(username,password);
            if (user != null){
                resultMap.put("flag", true);
                request.getSession().setAttribute("user",user);
            }else {
                resultMap.put("flag",false);
                resultMap.put("message","用户名或密码错误!");
            }
        } catch (NumberFormatException e) {
            resultMap.put("flag", false);
            resultMap.put("message", "登陆失败!");
            e.printStackTrace();
        }

        return resultMap;
    }

    private UserService userService = new UserServiceImpl();

    private Map update(HttpServletRequest request, HttpServletResponse response) {
        Map resultMap = new HashMap();
        try {
            Map<String, String[]> map = request.getParameterMap();
            User user = new User();
            BeanUtils.populate(user, map);
            userService.update(user);
            resultMap.put("flag", true);
        } catch (Exception e) {
            resultMap.put("flag", false);
            resultMap.put("message", "修改失败!");
            e.printStackTrace();
        }

        return resultMap;
    }

    private Map delete(HttpServletRequest request, HttpServletResponse response) {
        Map resultMap = new HashMap();
        try {
            String userId = request.getParameter("userId");
            userService.delete(userId);
            resultMap.put("flag", true);
        } catch (Exception e) {
            resultMap.put("flag", false);
            resultMap.put("message", "删除失败!");
            e.printStackTrace();
        }

        return resultMap;
    }

    private Map add(HttpServletRequest request, HttpServletResponse response) {
        Map resultMap = new HashMap();
        try {
            Map<String, String[]> map = request.getParameterMap();
            User user = new User();
            BeanUtils.populate(user, map);
            userService.add(user);
            resultMap.put("flag", true);
        } catch (Exception e) {
            resultMap.put("flag", false);
            resultMap.put("message", "添加失败!");
            e.printStackTrace();
        }

        return resultMap;
    }

    private Map findByPage(HttpServletRequest request, HttpServletResponse response) {
        Map resultMap = new HashMap();
        try {
            String currentPageStr = request.getParameter("currentPage");
            int currentPage = 1;
            if (currentPageStr != null && !"".equals(currentPageStr)) {
                currentPage = Integer.parseInt(currentPageStr);
            }
            PageInfo info = userService.findByPage(currentPage);
            resultMap.put("flag", true);
            resultMap.put("resultData", info);
        } catch (NumberFormatException e) {
            resultMap.put("flag", false);
            resultMap.put("message", "查询失败!");
            e.printStackTrace();
        }

        return resultMap;
    }
}
